package cn.tedu._05mvcboot034.controller;

import cn.tedu._05mvcboot034.common.response.JsonResult;
import cn.tedu._05mvcboot034.common.response.StatusCode;
import cn.tedu._05mvcboot034.mapper.UserMapper;
import cn.tedu._05mvcboot034.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot034.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot034.pojo.entity.Article;
import cn.tedu._05mvcboot034.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Slf4j
@Api(tags = "用户模块")
@Validated
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("用户登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody @Validated UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.debug("userLoginDTO = " + userLoginDTO);
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        UserVO userVO = userMapper.selectUser(username, password);
        log.debug("userVO = " + userVO);
        if(userVO != null){
            session.setAttribute("user", userVO);
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
    }

    @ApiOperation("发表文章功能")
    @PostMapping("article")
    public JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session){
        log.debug("userArticleDTO = "+userArticleDTO);
        UserVO userVO = (UserVO) session.getAttribute("user");
        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(userVO.getId());
        log.debug("article =" +article);
        userMapper.insertArticle(article);
        return JsonResult.ok();
    }
}
